package org.csu.jpetstore_users_backend_pj.interceptors;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.csu.jpetstore_users_backend_pj.util.JwtUtil;
import org.csu.jpetstore_users_backend_pj.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor{



    //preHandle方法会在请求到达接口之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{

        String token = request.getHeader("Authorization");
        //这里会直接验证这个token我们不使用if
        try {
            //redis验证Token 通过了才解析map
            Map<String, Object> map = JwtUtil.ParseToken(token);
            //放行
            return true;
        }catch (Exception e) {
            //不放行
            response.setStatus(401);
            return false;
        }
        //这里return会return给谁
    }

    //请求结束执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
